package lauglog.servlet;

/*
 * This class is used to commit events as they are completed by users
 * 
 */

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import lauglog.bean.UserBean;
import lauglog.bean.UserEventsBean;

/**
 *
 * @author Waseem Mir
 */
@WebServlet(name = "EventDone", urlPatterns = {"/EventDone"})
public class EventDoneServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            //get reference to userId
            UserBean ub = (UserBean)(request.getSession().getAttribute("user"));
            int userId = ub.getUserID();
            
            //we are processing the request 
            String action = request.getParameter("type");
            if (action.equalsIgnoreCase("metric"))
                metricDone(userId,Integer.parseInt(request.getParameter("eventId")),Integer.parseInt(request.getParameter("value")));
            else if (action.equalsIgnoreCase("static"))
                staticDone(userId,Integer.parseInt(request.getParameter("eventId")));
            else if (action.equalsIgnoreCase("bp"))
                bpDone(userId,Integer.parseInt(request.getParameter("eventId")),Integer.parseInt(request.getParameter("systolic")),Integer.parseInt(request.getParameter("diastolic")));
            else;
            
            //update the todays events bean and redirect back to the dashboard
            UserEventsBean ueb = (UserEventsBean)(request.getSession().getAttribute("todaysEvents"));
            for (int i=0; i<ueb.getListEvents().size(); i++)
            {
                if (ueb.getListEvents().get(i).getEventID() == Integer.parseInt(request.getParameter("eventId")))
                {
                    ueb.getListEvents().remove(i);
                    break;
                }
            }
            
            response.sendRedirect("dashboard.jsp");
            
        } finally {            
            out.close();
        }
    }
    
    private void metricDone(int userId, int eventId, int value)
    {
        //Initiate variables for database queries
        String url = "jdbc:mysql://localhost/lauglog";
        String dbUserName = "root";
        String dbPassword = "";
        String driver = "com.mysql.jdbc.Driver";
        
        Connection con = null;
        try{
            
            //Make the connection
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, dbUserName, dbPassword);
            
            //execute a statement which inserts a row into the metric_data table

            PreparedStatement metricData = con.prepareStatement("INSERT INTO metric_data (DateTime,EventId,RecordedValue,UserId) VALUES (NOW(),?,?,?)");
            metricData.setInt(1,eventId);
            metricData.setInt(2,value);
            metricData.setInt(3,userId);            
            metricData.executeUpdate();
            
            //now we have to update the alerts table just in case this value is over
            PreparedStatement alertsStatement = con.prepareStatement("SELECT AlertType,AlertNumber FROM event_alerts WHERE EventId=?");
            alertsStatement.setInt(1,eventId);
            ResultSet alertRs = alertsStatement.executeQuery();
            
            //any such alerts exist?
            boolean alertsExist = alertRs.first();
            
            //if so, then we need to add a tuple to alerts table
            if(alertsExist)
            {
                //get the type and number of the alert
                String alertType = alertRs.getString("AlertType");
                int alertNumber = alertRs.getInt("AlertNumber");
                
                //if the alert has been triggered, then add alert tuple
                if ((alertType.equals("over") && value>alertNumber) || (alertType.equals("under") && value<alertNumber))
                {
                    //get all the information necessary to insert tuple
                    int planId;
                    String userName;
                    String eventName;

                    //get the associated planId
                    PreparedStatement plandIdStatement = con.prepareStatement("SELECT PlanId FROM events WHERE EventId=?");
                    plandIdStatement.setInt(1,eventId);
                    ResultSet plandIdRs = plandIdStatement.executeQuery();
                    plandIdRs.first();
                    planId = plandIdRs.getInt("PlanId");

                    //get the users name
                    PreparedStatement userNameStatement = con.prepareStatement("SELECT FirstName,LastName FROM users WHERE UserId=?");
                    userNameStatement.setInt(1,userId);
                    ResultSet userNameRs = userNameStatement.executeQuery();
                    userNameRs.first();
                    userName = userNameRs.getString("FirstName")+" "+userNameRs.getString("LastName");

                    //get the event name
                    PreparedStatement eventNameStatement = con.prepareStatement("SELECT Name FROM events WHERE EventId=?");
                    eventNameStatement.setInt(1,eventId);
                    ResultSet eventNameRs = eventNameStatement.executeQuery();
                    eventNameRs.first();
                    eventName = eventNameRs.getString("Name");

                    PreparedStatement alertInsert = con.prepareStatement("INSERT INTO alerts (Date,PlanId,EventName,UserName,Value,UserId) VALUES (CURDATE(),?,?,?,?,?)");
                    alertInsert.setInt(1,planId);
                    alertInsert.setString(2,eventName);
                    alertInsert.setString(3,userName);
                    alertInsert.setInt(4,value);
                    alertInsert.setInt(5,userId);
                    alertInsert.executeUpdate();
                }
            }

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                con.close();
            }catch(Exception e){
                
            }
        }
    }
    private void staticDone(int userId, int eventId)
    {
        //Initiate variables for database queries
        String url = "jdbc:mysql://localhost/lauglog";
        String dbUserName = "root";
        String dbPassword = "";
        String driver = "com.mysql.jdbc.Driver";
        
        Connection con = null;
        try{
            
            //Make the connection
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, dbUserName, dbPassword);
            
            //execute a statement which inserts a row into the static_data table

            PreparedStatement staticData = con.prepareStatement("INSERT INTO static_data (DateTime,EventId,Completed,UserId) VALUES (NOW(),?,1,?)");
            staticData.setInt(1,eventId);
            staticData.setInt(2,userId);
            staticData.executeUpdate();

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                con.close();
            }catch(Exception e){
                
            }
        }
        
    }
    private void bpDone(int userId, int eventId, int systolic, int diastolic)
    {
        //Initiate variables for database queries
        String url = "jdbc:mysql://localhost/lauglog";
        String dbUserName = "root";
        String dbPassword = "";
        String driver = "com.mysql.jdbc.Driver";
        
        Connection con = null;
        try{
            
            //Make the connection
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, dbUserName, dbPassword);
            
            //execute a statement which inserts a row into the bp_data table

            PreparedStatement bpData = con.prepareStatement("INSERT INTO bp_data (DateTime,EventId,Systolic,Diastolic,UserId) VALUES (NOW(),?,?,?,?)");
            bpData.setInt(1,eventId);
            bpData.setInt(2,systolic);
            bpData.setInt(3,diastolic);
            bpData.setInt(4,userId);
            bpData.executeUpdate();
            
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                con.close();
            }catch(Exception e){
                
            }
        }
        
        
        
    }
        // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
}
